import { forIn } from "lodash";
import { createElementVNode } from "vue";
// import WaterMark from 'l-watermark'

/**
 * 等待一定时间后继续执行（async中
 * @param time 等待时间
 * @returns a Promise
 */
export const timeSleep = (time: number) => {
	return new Promise((success) => {
		setTimeout(() => {
			success("");
		}, time);
	});
};

/**
 * 动态引入js文件
 * @param src 链接
 * @param callback 状态变化的回调
 * @returns
 */
export const loadScript = (src: string) => {
	const head = document.getElementsByTagName("head")[0];
	const script = document.createElement("script");
	script.type = "text/javascript";
	script.src = src;
	return new Promise((ok) => {
		script.onload = script.onreadystatechange = function () {
			if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") {
				ok();
				script.onload = script.onreadystatechange = null;
			}
		};
		head.appendChild(script);
	});
};

/**
 * 打招呼
 */
export const hello = (uname) => {
	const h = new Date().getHours();
	let str = `哦亲爱的 ${uname} ，`;
	if (h <= 4 || h >= 23) str += "夜深了，早些歇息吧。";
	else if (h >= 5 && h <= 11) str += "早上好，今天也是元气满满的一天呢。";
	else if (h >= 12 && h <= 15) str += "中午好，今天午休了吗？";
	else if (h >= 16 && h <= 19) str += "下午好，晚上吃点啥呢？";
	else if (h >= 19 && h <= 22) str += "晚上好，要一起去看月亮嘛。";
	return str;
};

/**
 * 邮箱验证
 * @param mail 邮箱
 * @returns Boolean
 */
export const mailReg = (mail: string) => {
	return mail != "" ? /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/.test(mail) : true;
};

export const copyToShearPlate = (content: string, callback: Function) => {
	const textDom = document.createElement("textarea"); // 相比input支持换行
	textDom.readOnly = "readonly";
	textDom.value = content;
	document.body.appendChild(textDom);
	textDom.select();
	textDom.setSelectionRange(0, textDom.value.length);
	const result = document.execCommand("Copy");
	callback instanceof Function && callback(result);
	document.body.removeChild(textDom);
};

/**
 * @param fmt
 * @param date
 * @returns
 */
export const dateFormat = (date: Date | string | number, fmt: string = "YYYY/MM/DD hh:mm:ss") => {
	let ret;
	if (!date) return "";
	// Object.prototype.toString.call(date) != '[object Date]'
	if (!(date instanceof Date)) date = new Date(date);
	const opt = {
		"Y+": date.getFullYear().toString(), // 年
		"M+": (date.getMonth() + 1).toString(), // 月
		"D+": date.getDate().toString(), // 日
		"h+": date.getHours().toString(), // 时
		"m+": date.getMinutes().toString(), // 分
		"s+": date.getSeconds().toString(), // 秒
	};
	for (let k in opt) {
		ret = new RegExp("(" + k + ")").exec(fmt);
		if (ret) fmt = fmt.replace(ret[1], ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0"));
	}
	return fmt;
};

/**
 * 补0
 * @param num 要补充的数字
 * @param cover 补充到多少位？
 * @returns String
 */
export const replenish = (num, cover, tag) => {
	num = String(num);
	if (String(num).length > cover) return String(num);
	return (num = tag.repeat(cover).concat(num).slice(-cover));
};

/**
 * 正则们
 *
 */
export const regs = {
	account: /^[0-9]{8,16}$/,
	phoneNumber: /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/,
	email: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
	name: /^[\u4E00-\u9FA5A-Za-z]{2,}$/,
	idcard: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
	qq: /^[1-9][0-9]{4,14}$/,
	//数字+字母、8~16
	pass: /^(?=.*[0-9])(?=.*[a-zA-Z])[0-9A-Za-z~!@#$%^&*._?]{8,16}$/,
	wechat: /^[a-zA-Z][a-zA-Z\d_-]{5,19}$/,
};

/**
 * 上传图片
 * @param file 文件
 * @returns
 */
export const uploadFile = async (file) => {};

/**
 * File => String
 */
export const FileToBase64 = (file) => {
	return new Promise((resolve, reject) => {
		const reader = new FileReader();
		let fileResult = "";
		reader.readAsDataURL(file);
		reader.onload = () => {
			fileResult = reader.result;
		};
		reader.onerror = (error) => reject(error);
		reader.onloadend = () => resolve(fileResult);
	});
};

/**
 * url(http) -> base64
 */
export const urlToBase64 = (imgsrc) => {
	return new Promise((ok, no) => {
		const image = new Image();
		image.setAttribute("crossOrigin", "anonymous");
		image.onload = function () {
			const canvas = document.createElement("canvas");
			canvas.width = image.width;
			canvas.height = image.height;
			const context = canvas.getContext("2d");
			context.drawImage(image, 0, 0, image.width, image.height);
			const base64_str = canvas.toDataURL("image/png");
			ok(base64_str);
		};
		image.src = imgsrc;
	});
};

/**
 * 下载base64
 */
export const exportFile = (base64_str, fileName) => {
	const link = document.createElement("a");
	link.style.display = "none";
	link.href = base64_str;
	link.setAttribute("download", fileName);
	document.body.appendChild(link);
	link.click();
	document.body.removeChild(link);
	window.URL.revokeObjectURL(base64_str);
};

/**
 * return required rules
 */
export const requiredRules = (requiredlist = {}, conf) => {
	let { addtext = "不能为空", trigger = "blur" } = conf || {};
	const rules = {};
	forIn(requiredlist, (value, key) => {
		rules[key] = { required: true, message: `${value}${addtext}`, trigger };
	});
	return rules;
};

/**
 * base64图片加水印
 */
export const addwatermark = ({ target, text }) =>
	new Promise((ok) => {
		WaterMark.image({
			target,
			text,
			color: "rgba(0, 0, 0, 0.4)",
			fontSize: 28,
			cSpace: 60,
			// secret: true,
			success: (e) => {
				ok(e);
			},
		});
	});

/**
 * base64转File
 */

export const base64ToFile = (dataurl, filename = "图片.png") => {
	const arr = dataurl.split(",");
	const mime = arr[0].match(/:(.*?);/)[1];
	const bstr = atob(arr[1]);
	let n = bstr.length;
	const u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new File([u8arr], filename, { type: mime });
};
